#include <Arduino.h>

// 修正的引脚定义
#define L_EN_PIN_L   32   // 左侧使能
#define R_EN_PIN_L   33   // 右侧使能
#define L_PWM_PIN_L  25   // 左侧PWM（正转）
#define R_PWM_PIN_L  26   // 右侧PWM（反转）
#define L_EN_PIN_R   5   // 左侧使能
#define R_EN_PIN_R   17   // 右侧使能
#define L_PWM_PIN_R  16   // 左侧PWM（正转）
#define R_PWM_PIN_R  4   // 右侧PWM（反转）
#define POTENTIOMETER_input_PIN 34// 使用ESP32的ADC引脚
#define Potentiometer_PIN 0
#define Switch_digital_PIN 1
#define Direction_digital_PIN_POS 27
#define Direction_digital_PIN_NEG 14


// 使用通道0/1控制PWM
#define PWM_CH_L 0
#define PWM_CH_R 1

const int freq = 25000;    // 25kHz PWM频率
const int resolution = 8;  // 8位分辨率(0-255)
int speed=0,potentionmeter=0;
int direction_POS=0,direction_NEG=0;

void setup() {
  Serial.begin(115200);
  // 初始化使能引脚
  pinMode(L_EN_PIN_L, OUTPUT);
  pinMode(R_EN_PIN_L, OUTPUT);
  pinMode(L_EN_PIN_R, OUTPUT);
  pinMode(R_EN_PIN_R, OUTPUT);
  pinMode(Direction_digital_PIN_POS,INPUT);
  pinMode(Direction_digital_PIN_NEG,INPUT);
  digitalWrite(L_EN_PIN_L, HIGH);  // 默认使能电机
  digitalWrite(R_EN_PIN_L, HIGH);
  digitalWrite(L_EN_PIN_R, HIGH);  // 默认使能电机
  digitalWrite(R_EN_PIN_R, HIGH);

  // 配置PWM通道
  ledcSetup(PWM_CH_L, freq, resolution);
  ledcAttachPin(L_PWM_PIN_L, PWM_CH_L);
  ledcAttachPin(L_PWM_PIN_R, PWM_CH_L);
  ledcSetup(PWM_CH_R, freq, resolution);
  ledcAttachPin(R_PWM_PIN_L, PWM_CH_R);
  ledcAttachPin(R_PWM_PIN_R, PWM_CH_R);
}

// 统一函数签名：使用单一速度参数
void setMotor(int speed,int direction_POS,int direction_NEG) {
  speed = constrain(speed, -255, 255);  // 限制速度范围
  if(direction_POS==LOW&&direction_NEG==LOW) {speed=0; goto exit;};
  if(direction_NEG==HIGH) goto negative;
    ledcWrite(PWM_CH_L, speed);  // 正转
    ledcWrite(PWM_CH_R, 0);
    goto end;
    negative:ledcWrite(PWM_CH_L, 0);
    ledcWrite(PWM_CH_R, speed);  // 反转
    goto end;
    exit:ledcWrite(PWM_CH_L, 0);  // 停止
    ledcWrite(PWM_CH_R, 0);
    end:;
}

void stopMotor() {
  digitalWrite(L_EN_PIN_L, LOW);
  digitalWrite(L_EN_PIN_R, LOW);   // 禁用驱动
  digitalWrite(R_EN_PIN_R, LOW);
  digitalWrite(R_EN_PIN_L, LOW); 
  ledcWrite(PWM_CH_L, 0);      // 停止PWM输出
  ledcWrite(PWM_CH_R, 0);
  
  // 恢复使能状态
  delay(100);
  digitalWrite(L_EN_PIN_L, HIGH);
  digitalWrite(L_EN_PIN_R, HIGH);
  digitalWrite(R_EN_PIN_L, HIGH);
  digitalWrite(L_EN_PIN_R, HIGH);
}
void loop() {
  potentionmeter=analogRead(POTENTIOMETER_input_PIN);
  speed=(potentionmeter/4095.0)*255;
  direction_POS=digitalRead(Direction_digital_PIN_POS);
  direction_NEG=digitalRead(Direction_digital_PIN_NEG);
  Serial.println(potentionmeter);
  Serial.println(speed);
  setMotor(speed,direction_POS,direction_NEG);     // 正转
  delay(200);
}